﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using FanaticRock.BilibiliShell.Models;
using FanaticRock.Core.DI;
using FanaticRock.Core.Extensions;
using FanaticRock.Core.Interfaces;
using FanaticRock.Core.ServiceInterfaces;
using Microsoft.Web.WebView2.Core;

namespace FanaticRock.BilibiliShell.Views
{
    /// <summary>
    /// ShellView.xaml 的交互逻辑
    /// </summary>
    [InjectMe(LifeTimeType = InjectMeAttribute.LifeTimeEnum.Trans)]
    public partial class ShellView : UserControl, ILogger
    {
        private ILocalDbService _localDbService;

        public ShellView(ILocalDbService localDbService)
        {
            _localDbService = localDbService;

            InitializeComponent();
        }

        private async Task<IEnumerable<CoreWebView2Cookie>> GetCookies()
        {
            var cookies = await PART_WebView
                .CoreWebView2
                .CookieManager.
                GetCookiesAsync("https://www.bilibili.com");
            return cookies;
        }

        ///<summary>保存 Cookies</summary>
        private async Task SaveCookies()
        {
            foreach (var cookie in await GetCookies())
            {
                var id = cookie.Name;
                var value = cookie.Value;
                var bilibiliCookieInfo = new BilibiliCookieInfo(id, value);
                this.Info($"ShellView.SaveCookies: info {bilibiliCookieInfo}");
                await _localDbService.UpsertAsync(bilibiliCookieInfo);
            }
        }



        private async void PART_Close_Click(object sender, RoutedEventArgs e)
        {
            IsEnabled = false;

            await SaveCookies();
            Window.GetWindow(this).Close();


        }

        private void PART_Close_MouseEnter(object sender, MouseEventArgs e)
        {
            var anim = new DoubleAnimation(0.7, new Duration(TimeSpan.FromMilliseconds(700)));
            anim.EasingFunction = new QuinticEase() { EasingMode = EasingMode.EaseOut };
            PART_Mask.BeginAnimation(OpacityProperty, anim);
        }

        private void PART_Close_MouseLeave(object sender, MouseEventArgs e)
        {
            var anim = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(400)));
            anim.EasingFunction = new QuinticEase() { EasingMode = EasingMode.EaseOut };
            PART_Mask.BeginAnimation(OpacityProperty, anim);
        }
    }
}
